package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.ContractMultiListAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseOriginal;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.OrderQueryParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.rContractListMain;
import com.isunland.managesystem.utils.MenuUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 对象功能:  未关联合同列表
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/7/25 15:20
 */
public class ContractNoRelationListFragment extends BaseListFragment {
  private static final int MENU_ITEM_QUERY = 0;
  private static final int MENU_ITEM_RELATE = 1;
  ArrayList<rContractListMain> mList;
  private ContractMultiListAdapter mAdapter;
  private OrderQueryParams mQueryParams;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom("未关联合同");
    mList = new ArrayList<>();
    mQueryParams = new OrderQueryParams();
    mQueryParams.setBeginregDate(
        MyDateUtil.format(MyDateUtil.getBeforeMonth(3), MyDateUtil.TYPE_DATE));
    mQueryParams.setEndregDate(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    MenuUtil.addSubMenu(menu, MENU_ITEM_QUERY, R.string.query);
    MenuUtil.addSubMenu(menu, MENU_ITEM_RELATE, R.string.setRelate);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    if (MENU_ITEM_QUERY == item.getItemId()) {
      //查询
      ContractQueyActivity.newInstance(this, ContractQueyActivity.class, mQueryParams, 0);
    }
    if (MENU_ITEM_RELATE == item.getItemId()) {
      //设置关联合同
      getContractIds();
    }
    return super.onOptionsItemSelected(item);
  }

  private void getContractIds() {
    if (mList != null || mList.size() != 0) {
      StringBuilder bufferIds = new StringBuilder();
      for (int i = mList.size() - 1; i >= 0; i--) {
        rContractListMain item0 = mList.get(i);
        if (item0 == null) continue;
        String id = item0.getId();
        if (mAdapter.isCheckedItem(item0)) {
          if (bufferIds.length() > 0) {
            bufferIds.append(",").append(id);
          } else {
            bufferIds.append(id);
          }
        }
      }
      if (bufferIds.length() == 0) {
        ToastUtil.show("请先选中要操作的记录");
      } else {
        volleyPostRelate(bufferIds.toString());
      }
    }
  }

  //设置关联合同
  private void volleyPostRelate(String ids) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RELATE_CONTRACT);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("projectId", mBaseParams.getId());
    params.put("contractIds", ids);
    params.put("dataType", "project");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(json, SuccessMessage.class);
          if (success != null
              && success.getResult() != null
              && SuccessMessage.SUCCESS.equalsIgnoreCase(success.getResult())) {
            ToastUtil.show(R.string.success_operation);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }
    });
  }

  @Override public String getUrl() {
    return ApiConst.URL_CONTRACT_LIST_RECEIPT;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("curPage", "1");
    params.put("pageSize", "10000");
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("isPaging", "1");
    params.put("dataStatus", "checkPass");
    params.put("beginregDate", mQueryParams.getBeginregDate());
    params.put("endregDate", mQueryParams.getEndregDate());
    params.put("contractCode", mQueryParams.getCode());
    params.put("contractName", mQueryParams.getName());
    params.put("relationProjectId", mBaseParams.getId());
    params.put("orderField", "reg_date");
    params.put("orderSeq", "desc");
    return params.getParams();
  }

  @Override public void resolveResponse(String json) {
    BaseOriginal<rContractListMain> original =
        new Gson().fromJson(json, new TypeToken<BaseOriginal<rContractListMain>>() {
        }.getType());
    List<rContractListMain> rows = original.getRows();

    if (original != null && Base.SUCCESS == original.getResult()) {
      mList.clear();
      mList.addAll(rows);
      mAdapter = new ContractMultiListAdapter(getActivity(), mList, null);
      setListAdapter(mAdapter);
    } else {
      ToastUtil.show("获取数据失败");
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == 0) {
      //查询
      mQueryParams = (OrderQueryParams) data.getSerializableExtra(BaseFragment.EXTRA_PARAMS);
      volleyPost();
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
